import axios from 'axios'
import { ElMessage } from 'element-plus'

class Request {
  constructor(options = {}) {
    this.options = options
    this.instance = axios.create({
      baseURL: import.meta.env.VITE_API_BASE_URL,
      timeout: 10000,
      ...options
    })

    // 请求拦截
    this.instance.interceptors.request.use(
      (config) => {
        const token = localStorage.getItem('token')
        if (token) {
          config.headers.Authorization = `Bearer ${token}`
        }
        return config
      },
      (error) => {
        return Promise.reject(error)
      }
    )

    // 响应拦截
    this.instance.interceptors.response.use(
      (response) => {
        const { code, data, message } = response.data

        if (code === 200) {
          return data
        } else {
          ElMessage.error(message || '请求失败')
          return Promise.reject(new Error(message || 'Error'))
        }
      },
      (error) => {
        let msg = ''
        const status = error.response?.status
        
        if (status === 401) {
          msg = '身份认证失败，请重新登录'
          // 跳转登录逻辑
        } else if (status === 403) {
          msg = '拒绝访问'
        } else if (status === 404) {
          msg = '请求资源不存在'
        } else if (status === 500) {
          msg = '服务器错误'
        } else {
          msg = error.message || '未知错误'
        }

        ElMessage.error(msg)
        return Promise.reject(error)
      }
    )
  }

  request(config) {
    return this.instance.request(config)
  }

  get(url, params, config) {
    return this.instance.get(url, { params, ...config })
  }

  post(url, data, config) {
    return this.instance.post(url, data, config)
  }

  put(url, data, config) {
    return this.instance.put(url, data, config)
  }

  delete(url, params, config) {
    return this.instance.delete(url, { params, ...config })
  }
}

// 创建请求实例
const http = new Request()

export default http